package com.sq.partner.manager.controller;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.math.BigDecimal;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFDataFormat;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.util.CellRangeAddress;
import org.apache.poi.hssf.util.HSSFColor;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.sq.partner.manager.common.Config;
import com.sq.partner.manager.common.Constants;
import com.sq.partner.manager.common.DictCache;
import com.sq.partner.manager.common.Result;
import com.sq.partner.manager.dao.IGatewayChannelAppDao;
import com.sq.partner.manager.mybatis.model.DictAddrDto;
import com.sq.partner.manager.mybatis.model.DictDto;
import com.sq.partner.manager.mybatis.model.GatewayApp;
import com.sq.partner.manager.mybatis.model.GatewayAppTranstype;
import com.sq.partner.manager.mybatis.model.GatewayChannelApp;
import com.sq.partner.manager.mybatis.model.GatewayChannelDemandConfig;
import com.sq.partner.manager.mybatis.model.GatewayChannelInfo;
import com.sq.partner.manager.mybatis.model.GatewayChannelIp;
import com.sq.partner.manager.mybatis.model.GatewayChannelTranstype;
import com.sq.partner.manager.mybatis.model.GatewayChannelUser;
import com.sq.partner.manager.mybatis.model.GatewaySubChannel;
import com.sq.partner.manager.mybatis.model.GatewayUser;
import com.sq.partner.manager.mybatis.model.TradInsuPlan;
import com.sq.partner.manager.mybatis.model.TreeDto;
import com.sq.partner.manager.service.IGatewayAppService;
import com.sq.partner.manager.service.IGatewayChannelAppService;
import com.sq.partner.manager.service.IGatewayChannelInfoConfigService;
import com.sq.partner.manager.service.IGatewayClearCacheManager;
import com.sq.partner.manager.service.IGatewayInsureService;
import com.sq.partner.manager.service.IGatewaySubChannelService;
import com.sq.partner.manager.util.JsonUtils;
import com.sq.partner.manager.util.LogUtil;
import com.sq.partner.manager.util.Page;
import com.sq.partner.manager.util.SqlUtil;
import com.sq.partner.manager.util.StrUtil;
import com.sq.partner.manager.webservice.LifeCoreClient;

/**
 * 
 * @author duguangwei
 * 合作伙伴配置
 */
@Controller
@RequestMapping(value = "/channelManage")
public class ChannelInfoConfigController {
	private static Logger logger = LogUtil.getLog(ChannelInfoConfigController.class);
	@Resource
	private IGatewayChannelInfoConfigService channelInfoConfigService;
	@Resource
	private IGatewayAppService appService;
	@Resource
	private IGatewaySubChannelService subChannelService;
	@Resource
	private IGatewayChannelAppService gatewayChannelAppService;
	@Resource
	private IGatewayInsureService gatewayInsureService;
	@Resource
	IGatewayClearCacheManager gatewayClearCacheManager;
	@Resource
	IGatewayChannelAppDao gatewayChannelAppDao;
	@RequestMapping("/channelInfoConfig")
	public String channelInfoConfig(ModelMap model) throws Exception {
		
		//获取单位证件类型
		List<DictDto> list = DictCache.getDict(Constants.DICT_COM_ID_TYPE);
		// modified by guozizhou@20150409 for bei jing code begin
		//获取企业性质
		List<DictDto> unitLs = querySubElementList(Constants.DICT_UNIT_TYPE,"115");
		//获取行业类型
		List<DictDto> industLs = querySubElementList(Constants.DICT_INDUSTRY_TYPE,"130");
		//获取地址信息-一级默认省
		List<DictAddrDto> provinceLs= queryAddrList(Constants.DICT_PROVINCE_CODE);
		//Constants.DICT_ID_TYPE
		List<DictDto> linkManIdTypeLs = DictCache.getDict(Constants.DICT_ID_TYPE);
		//获取合作伙伴分类信息
		List<DictDto> channelSortList = DictCache.getDict(Constants.DICT_CHANNEL_SORT);
		model.put("idTypeList", list); 
		model.put("unitLs", unitLs); 
		model.put("industLs", industLs); 
		model.put("provinceLs", provinceLs);
		model.put("linkManIdTypeLs", linkManIdTypeLs);
		model.put("channelSortList", channelSortList);
		//modified by guozizhou@20150409 for bei jing code end
	   return "appManage/channelInfoConfig";
	}
	
	/**
	 * 根据上一级的code查询下一级地址List<app>
	 * @param session
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/queryAddrList")
	@ResponseBody
    public List<DictAddrDto> queryAddrList(String parentCode) throws Exception {
		DictAddrDto dictAddr = new DictAddrDto();
		dictAddr.setParentCode(parentCode);
		return channelInfoConfigService.queryProvinceCityCounty(dictAddr);
    }
	
	/**
	 * 
	 * @param idType,parentCode
	 * @return List<DictDto>
	 * @throws Exception
	 */
	@RequestMapping("/querySubElementList")
	@ResponseBody
    public List<DictDto> querySubElementList(String idType,String parentCode) throws Exception {
		DictDto dict = new DictDto();
		dict.setCodeType(idType);
		dict.setParentCode(parentCode);
		return channelInfoConfigService.querySubElementList(dict);
    }
	
	/**
	 * 查询有权限的合作伙伴对应的List<app>
	 * @param session
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/queryAppList")
	@ResponseBody
    public List<GatewayApp> queryAppList(HttpSession session) throws Exception {
		GatewayUser gatewayuser=(GatewayUser) session.getAttribute(Constants.SESSION_USER);
		GatewayApp gatewayApp=new GatewayApp();
		gatewayApp.setDepts(gatewayuser.getDepts());
		return appService.queryList(gatewayApp);
    }
	
	/**
	 * 查找所有app(List<GatewayApp>)
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/queryAllAppList")
	@ResponseBody
	public List<GatewayApp> queryAllAppList() throws Exception{
		return appService.queryAllAppList();
	}
	
	/**
	 * 分页条件查询ChannelInfo
	 * @param pageIndex
	 * @param appid
	 * @param channelCode
	 * @return
	 * @throws Exception 
	 */
	@RequestMapping("/queryByCriteria")
	@ResponseBody
	public Page queryByCriteria(HttpSession session, Integer pageIndex,String channelName,String channelCode) throws Exception{
		GatewayUser user = (GatewayUser) session.getAttribute(Constants.SESSION_USER);
		
		GatewayChannelInfo channelInfo = new GatewayChannelInfo();
		channelInfo.setChannelName(channelName);
		channelInfo.setChannelCode(channelCode);
		//总行和分行
		boolean isHQFlag = false;
		if(null != user && StrUtil.isNotEmpty(user.getDepartmentStr())){
			isHQFlag = user.getDepartmentStr().contains(Constants.HQ_BRANCH_CODE);
		}
		user.setHQFlag(isHQFlag);
		
		Page channelInfoPage = channelInfoConfigService.queryByCriteria(pageIndex, channelInfo, user);
		
		return channelInfoPage;
	}
	
	/**
	 * 根据channelCode查询相应的channelInfo
	 * @param channelCode
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/queryChannelInfoByChannelCode")
	@ResponseBody
	public GatewayChannelInfo queryChannelInfoByChannelCode(String channelCode) throws Exception{
		GatewayChannelInfo channelInfo = channelInfoConfigService.queryChannelInfoByChannelCode(channelCode);
		return channelInfo;
	}
	
	/**
	 * 添加channelInfo
	 * @param channelCode
	 * @param channelName
	 * @param fkAppId
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/saveOrUpdateChannelInfo")
	@ResponseBody
	public Result saveOrUpdateChannelInfo(HttpSession session,String isThirdPlan,String channelCode,String channelName,String channelSort,String fkAppId,String deptCode,String transType, String transUser, String transIp, String transRsa, String publicKey,String privateKey,String cooperatePublicKey , String flag , String is_Async,String afferentPolno,String estimateAmout,String estimateDes,String tbrEmail) throws Exception{
		if(!(channelInfoConfigService.checkIsHasPrivilege(session, deptCode))){
			return Result.error("权限不足，无权操作该合作伙伴!");
		}else if(StrUtil.isEmpty(flag)){
			return Result.error("系统异常");
		}/*else if(StrUtil.isEmpty(fkAppId)){
			return Result.error("网关应用代码不能为空");
		}else if(fkAppId.length() > 20){
			return Result.error("网关应用代码错误");
		}*/else if(StrUtil.isEmpty(channelCode)){
			return Result.error("合作伙伴代码不能为空");
		}else if(!channelCode.matches("^[a-zA-Z_0-9]{1,30}$")){
			return Result.error("合作伙伴代码只支持字母数字下划线组合且长度不能大于30");
		}else if(StrUtil.isEmpty(channelName)){
			return Result.error("合作伙伴名称不能为空");
		}else if(channelName.length() > 50){
			return Result.error("合作伙伴名称长度不能超过50个字符");
		}else if(StrUtil.isEmpty(deptCode)){
			return Result.error("请选择所属机构");
		}
		
		GatewayUser user = (GatewayUser) session.getAttribute(Constants.SESSION_USER);
		Long operUser = user.getUserid();
		Date operTime = new Date();
		String status = "1";
		GatewayChannelInfo channelInfo = new GatewayChannelInfo(channelCode, channelName, transType, fkAppId, deptCode, status, operUser,transUser,transIp,transRsa, operTime, is_Async);
		channelInfo.setPublicKey(publicKey);
		channelInfo.setTbrEmail(tbrEmail);
		channelInfo.setPrivateKey(privateKey);
		channelInfo.setCooperatepublicKey(cooperatePublicKey);
		channelInfo.setIs_Async(is_Async);
		channelInfo.setAfferentPolno(afferentPolno);
		channelInfo.setIsThirdPlan(isThirdPlan);
		channelInfo.setChannelSort(channelSort);
		if(StrUtil.isNotEmpty(estimateAmout)){
			channelInfo.setEstimateAmout(estimateAmout);
		}
		if(StrUtil.isNotEmpty(estimateDes)){
			channelInfo.setEstimateDes(estimateDes);
		}
		//added by gzz@20150504 for 添加或者更新顶级信息到DB  begin
		GatewaySubChannel subChannel =   new GatewaySubChannel();
		subChannel.setSubChannelCode(channelCode);
		subChannel.setSubChannelName(channelName);
		subChannel.setFkChannelCode(channelCode);
		subChannel.setStatus("1");
		subChannel.setOperTime(operTime);
		subChannel.setOperUser(operUser);
		if("update".equalsIgnoreCase(flag))
		{
	 		subChannelService.saveOrUpdateSubChannel(subChannel, flag);
		}
		if("save".equalsIgnoreCase(flag)) {
			GatewaySubChannel checkPk = subChannelService.querySubChannelInfoById(subChannel.getSubChannelCode());
			if(null!= checkPk){
				return Result.error("该合作伙伴机构代码已经占用，请修改后再次保存！");
			}
	 		subChannelService.saveOrUpdateSubChannel(subChannel, flag);
		}
		//added by gzz@20150504 for 添加或者更新顶级信息到DB  end
		channelInfoConfigService.saveOrUpdateChannelInfo(channelInfo,flag);
		//添加成功后，根据合作伙伴的代码和名称，向核心发送投保人编码请求报文，返回结果保存到 channel_info 表的clientNo字段。
		if(flag.equals("save")){

//			String xmlStr = "";
//			String clientNo = LifeCoreClient.sendToCicHealth(xmlStr);
//			GatewayChannelInfo channelInfo2 = new GatewayChannelInfo();
//			channelInfo2.setChannelCode(channelCode);
//			channelInfo2.setClientNo(clientNo);
//			channelInfoConfigService.saveOrUpdateChannelInfo(channelInfo2,"update");	
			return Result.success("添加成功！");
		}else if(flag.equals("update")){
			return Result.success("修改成功！");
		}
		
		return null;
	}
	
	/**
	 * 删除ChannelInfo
	 * @param channelCode
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/deleteChannelInfoByChannelCode")
	@ResponseBody
	public Result deleteChannelInfoByChannelCode(HttpSession session, String channelCode, String deptCode) throws Exception{
		if(StrUtil.isEmpty(channelCode)){
			return Result.error("合作伙伴代码不能为空，操作失败！");
		}else if(StrUtil.isEmpty(deptCode)){
			return Result.error("合作伙伴所属机构代码不能为空，操作失败！");
		}
		if(!(channelInfoConfigService.checkIsHasPrivilege(session, deptCode))){
			return Result.error("权限不足，无权操作该合作伙伴!");
		}
		GatewayChannelInfo channelInfo = new GatewayChannelInfo();
		channelInfo.setChannelCode(channelCode);
		Result result = channelInfoConfigService.deleteChannelInfoByChannelCode(channelInfo);
		return result;
	}
	
	/**
	 * 更改合作伙伴所属的网关应用
	 * @param channelCode
	 * @param appId
	 * @return
	 * @throws Exception 
	 */
	@RequestMapping("/updateChannelAppId")
	@ResponseBody
	public String updateChannelAppId(String channelCode,String appId) throws Exception{
		GatewayChannelInfo channelInfo = new GatewayChannelInfo();
		channelInfo.setChannelCode(channelCode);
		channelInfo.setFkAppid(appId);
		channelInfoConfigService.updateChannelAppId(channelInfo);
		return "success";
	}
	
	/**
	 * 根据Appid查询与之对应的ChannelInfo
	 * @param fkAppid
	 * @return List<GatewayChannelInfo>
	 * @throws Exception 
	 */
	@RequestMapping("/loadChannelInfoByAppid")
	public @ResponseBody Page<GatewayChannelInfo> loadChannelInfoByAppid(String appId,HttpSession session) throws Exception{
		Page<GatewayChannelInfo> page = new Page<GatewayChannelInfo>();
		if(StrUtil.isEmpty(appId)){
			page.setResult("error");
			page.setMessage("网关应用代码不能为空");
			return page;
		}
		GatewayChannelInfo channelInfo = new GatewayChannelInfo();
		channelInfo.setFkAppid(appId);
		GatewayUser gatewayuser=(GatewayUser) session.getAttribute(Constants.SESSION_USER);
		channelInfo.setDepts(gatewayuser.getDepts());
		
		page.setType(channelInfo);
		return channelInfoConfigService.getListByDept(page);
	}
	/**
	 * 根据渠道ID 查询出渠道的交易名称
	 * 经全局搜索没有使用此方法 所以注释  noted by gzz@20150512
	
	@RequestMapping("/loadTransNameBychannelCode")
	public @ResponseBody Page loadTransNameBychannelCode(String channel_Code) throws Exception{
		Page page=new Page();
		if(StrUtil.isEmpty(channel_Code)){
			page.setResult("error");
			page.setMessage("合作伙伴代码不能为空");
			return page;
		}
		return channelInfoConfigService.getTranstypeBychannelCode(channel_Code);
	} */
	
	@RequestMapping("/queryList")
	public String queryList(Page page) throws Exception {
		if(null != page){
			page = channelInfoConfigService.getList(page);
		}
		return "success";
	}
	
	/**
	 * 根据channelCode查询相应的ChannelUser
	 * @param fkChannelCode
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/queryChannelUserByFkChannelCode")
	@ResponseBody
	public Page queryChannelUserByFkChannelCode(String channelCode,String appid) throws Exception{
		List<GatewayChannelUser> channelUserList = channelInfoConfigService.queryChannelUserByFkChannelCode(channelCode,appid);
		
		Page channelUserPage = new Page();
		channelUserPage.setData(channelUserList);
		return channelUserPage;
	}
	
	/**
	 * 根据channelUser属性查询相应的channelUser(返回一个channelUser对象)
	 * @param userName
	 * @param fkChannelCode
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/queryChannelUserByChannelUser")
	@ResponseBody
	public GatewayChannelUser queryChannelUserByChannelUser(String userName,String fkChannelCode) throws Exception{
		if(StrUtil.isEmpty(userName)){
			return null;
		}
		
		GatewayChannelUser user = new GatewayChannelUser();
		user.setUserName(userName);
		user.setFkChannelCode(fkChannelCode);
		GatewayChannelUser channelUser = channelInfoConfigService.queryChannelUserByChannelUser(user);
		return channelUser;
	}
	
	/**
	 * 根据channelUser属性删除相应的channelUser
	 * @param userName
	 * @param fkChannelCode
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/delChannelUserByChannelUser")
	@ResponseBody
	public Result delChannelUserByChannelUser(String userName,String fkChannelCode) throws Exception{
		GatewayChannelUser channelUser = new GatewayChannelUser();
		channelUser.setUserName(userName);
		channelUser.setFkChannelCode(fkChannelCode);
		
		channelInfoConfigService.delChannelUserByChannelUser(channelUser);
		return Result.success("删除成功");
	}
	
	/**
	 * 添加channelUser
	 * @param userName
	 * @param userPassword
	 * @param fkChannelCode
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/saveChannelUser")
	@ResponseBody
	public Result saveChannelUser(String userName,String userPassword,String fkChannelCode) throws Exception{
	
		if(StrUtil.isEmpty(fkChannelCode)){
			return Result.error("合作伙伴代码不能为空");
		}else if(fkChannelCode.length() > 30){
			return Result.error("合作伙伴代码长度不能超过30个字符");
		}else if(StrUtil.isEmpty(userName)){
			return Result.error("用户名不能为空");
		}else if(userName.length() > 50){
			return Result.error("用户名长度不能超过50个字符");
		}else if(StrUtil.isEmpty(userPassword)){
			return Result.error("用户密码不能为空");
		}else if(userPassword.length() > 50){
			return Result.error("用户密码长度不能超过50个字符");
		}
		
		GatewayChannelUser channelUser = new GatewayChannelUser();
		channelUser.setUserName(userName);
		channelUser.setUserPassword(userPassword);
		channelUser.setFkChannelCode(fkChannelCode);
		
		channelInfoConfigService.saveChannelUser(channelUser);
		
		return Result.success("添加成功");
	}
	
	/**
	 * 根据fkChannelCode查询相应的channelIp
	 * @param fkChannelCode
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/queryChannelIpByFkChannelCode")
	@ResponseBody
	public Page queryChannelIpByFkChannelCode(String fkChannelCode, String appid) throws Exception{
		GatewayChannelIp channelIp = new GatewayChannelIp();	
		channelIp.setFkChannelCode(fkChannelCode);
		channelIp.setAppId(appid);
		List<GatewayChannelIp> channelIpList = channelInfoConfigService.queryChannelIpByChannelIp(channelIp);
	
		Page channelIpPage = new Page();
		channelIpPage.setData(channelIpList);
		return channelIpPage;
	}
	
	/**
	 * 根据联合主键ipDes和fkChannelCode删除相应的ChannelIp
	 * @param fkChannelCode
	 * @param ipDes
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/delChannelIpByChannelIp")
	@ResponseBody
	public Result delChannelIpByChannelIp(String fkChannelCode,String ipDes) throws Exception{
		if(StrUtil.isEmpty(fkChannelCode)){
			return Result.success("合作伙伴代码不能为空");
		}else if(StrUtil.isEmpty(ipDes)){
			return Result.success("IP不能为空");
		}
		
		GatewayChannelIp channelIp = new GatewayChannelIp();
		channelIp.setIpDes(ipDes);
		channelIp.setFkChannelCode(fkChannelCode);
		
		channelInfoConfigService.delChannelIpByChannelIp(channelIp);
		return Result.success("删除成功");
	}
	
	/**
	 * 新增channelIp
	 * @param ipDes
	 * @param fkChannelCode
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/saveChannelIp")
	@ResponseBody
	public Result saveChannelIp(String ipDes,String fkChannelCode) throws Exception{
		if(StrUtil.isEmpty(fkChannelCode)){
			return Result.error("合作伙伴代码不能为空");
		}else if(fkChannelCode.length() > 30){
			return Result.error("合作伙伴代码长度不能超过30个字符");
		}else if(StrUtil.isEmpty(ipDes)){
			return Result.error("IP不能为空");
		}else if(ipDes.length() > 50){
			return Result.error("IP长度不能超过50个字符");
		}
		
		GatewayChannelIp channelIp = new GatewayChannelIp();
		channelIp.setIpDes(ipDes);
		channelIp.setFkChannelCode(fkChannelCode);
		channelInfoConfigService.saveChannelIp(channelIp);
		
		return Result.success("添加成功");
	}
	
	/**
	 * 检查输入的IP是否已经在该渠道中存在
	 * @param fkChannelCode
	 * @param ipDes
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/queryChannelIpByChannelIp")
	@ResponseBody
	public GatewayChannelIp queryChannelIpByChannelIp(String fkChannelCode,String ipDes) throws Exception{
	
		GatewayChannelIp channelIp = new GatewayChannelIp();
		channelIp.setIpDes(ipDes);
		channelIp.setFkChannelCode(fkChannelCode);
		
		GatewayChannelIp channelIpFind = null;

		List<GatewayChannelIp> channelIpList = channelInfoConfigService.queryChannelIpByChannelIp(channelIp);
		for (GatewayChannelIp ci : channelIpList) {
			channelIpFind = ci;
		}
		
		return channelIpFind;
	}
	
	/**
	 * 根据fkChannelCode查询相应的channelTranstype
	 * @param fkChannelCode
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/queryChannelTranstypeByFkChannelCode")
	@ResponseBody
	public Page queryChannelTranstypeByFkChannelCode(String fkChannelCode,String appid) throws Exception{
		GatewayChannelTranstype channelTranstype = new GatewayChannelTranstype();
		channelTranstype.setFkChannelCode(fkChannelCode);
		channelTranstype.setAppId(appid);
		List<GatewayChannelTranstype> channelTranstypeList = channelInfoConfigService.queryChannelTranstypeByChannelTranstype(channelTranstype);
		
		Page channelTranstypePage = new Page();
		channelTranstypePage.setData(channelTranstypeList);
		return channelTranstypePage;
	}
	
	/**
	 * 根据传入的channelCode查询在该channelTranstype中不存在，而在该channelCode所属app中存在的appTranstype
	 * @param appId
	 * @param channelCode
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/queryNotUsedAppTranstype")
	@ResponseBody
	public List<GatewayAppTranstype> queryNotUsedAppTranstype(String appId,String channelCode) throws Exception{
		GatewayChannelInfo channelInfo = new GatewayChannelInfo();
		channelInfo.setChannelCode(channelCode);
		channelInfo.setFkAppid(appId);
		List<GatewayAppTranstype> appTranstypeList = channelInfoConfigService.queryNotUsedAppTranstype(channelInfo);
		return appTranstypeList;
	}
	
	/**
	 * 根据transtypeId 删除相应的channelTranstype
	 * @param transtypeId
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/delChannelTranstypeByTranstypeId")
	@ResponseBody
	public Result delChannelTranstypeByTranstypeId(Long transtypeId,String channelCode) throws Exception{
		if(StrUtil.isEmpty(transtypeId)){
			return Result.success("交易类型ID不能为空");
		}
		
		
		channelInfoConfigService.delChannelTranstypeByChannelTranstype(transtypeId,channelCode);
		clearAllCacheByChannelCode(channelCode);
		return Result.success("删除成功");
	}
	
	/**
	 * 添加channelTranstype
	 * @param transCode
	 * @param transName
	 * @param fkChannelCode
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/saveChannelTranstype")
	@ResponseBody
	public Result saveChannelTranstype(String transCode,String transName,String fkChannelCode,String appId) throws Exception{
	
		if(StrUtil.isEmpty(fkChannelCode)){
			return Result.error("合作伙伴代码不能为空");
		}else if(fkChannelCode.length() > 30){
			return Result.error("合作伙伴代码长度不能超过30个字符");
		}else if(StrUtil.isEmpty(transCode)){
			return Result.error("交易代码不能为空");
		}else if(transCode.length() > 20){
			return Result.error("交易代码长度不能超过20个字符");
		}else if(StrUtil.isEmpty(transName)){
			return Result.error("交易名称不能为空");
		}else if(transCode.length() > 50){
			return Result.error("交易名称长度不能超过50个字符");
		}else if(StrUtil.isEmpty(appId)){
			return Result.error("应用代码不能为空");
		}
		
		GatewayChannelTranstype channelTranstype = new GatewayChannelTranstype();
		channelTranstype.setFkChannelCode(fkChannelCode);
		channelTranstype.setTransCode(transCode);
		channelTranstype.setTransName(transName);
		channelTranstype.setAppId(appId);
		channelInfoConfigService.saveChannelTranstype(channelTranstype);
		clearAllCacheByChannelCode(fkChannelCode);
		return Result.success("添加成功");
	}
	
	/**
	 * 查询当前登录用户的权限机构及其分机构（分公司-- deptCode.length()==2 ）
	 * @param session
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/queryBranchDept")
	@ResponseBody
	public List<TreeDto> queryBranchDept(HttpSession session) throws Exception {
		GatewayUser user = (GatewayUser) session.getAttribute(Constants.SESSION_USER);
		List<TreeDto> deptTree = channelInfoConfigService.queryBranchDeptOfOneUser(user);
		return deptTree;
	}
	
	
	
	/**
	 * 生成投保人编码
	 * @param channelCode
	 * @param channelName
	 * @param idType
	 * @param idNo
	 * @param deptNo
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/createClientNo")
	public @ResponseBody Result getClientNo(String channelCode,
			String channelName, String idType, String idNo, String deptNo,
			String socialNo, String orgProperty, String tradeCode,
			String address1, String address2, String address3, String city,
			String channelNameEn, String corporateDelegate, String telNo,
			String faxNo, String postCode, String address, String linkManName,
			String linkManCertificateType, String linkManCertificateNo,
			String linkManTel, String linkManAddress, String linkManPostCode,
			String linkManMobileNo,String createClientNoFlag) throws Exception {
		
		if(StrUtil.isEmpty(channelCode)){
			return Result.error("合作伙伴代码不能为空");
		}

		if(StrUtil.isEmpty(channelName)){
			return Result.error("合作伙伴名称不能为空");
		}
		
		if(StrUtil.isEmpty(deptNo)){
			return Result.error("机构代码不能为空");
		}
		
		if(StrUtil.isEmpty(idType)){
			return Result.error("证件类型不能为空");
		}else{
			if("0".equals(idType)){
				return Result.error("请选择证件类型");
			}
		}

		if(StrUtil.isEmpty(idNo)){
			return Result.error("证件号码不能为空");
		}
		// modified by guozizhou@20150409 for bei jing code begin
		//北京分行编码特殊处理
		if("11".equalsIgnoreCase(deptNo))
		{
			if(null == socialNo || "".equals(socialNo)){
				return Result.error("社保登记号不能为空");
			}
			if(StrUtil.isEmpty(orgProperty)){
				return Result.error("企业性质不能为空");
			}
			if(StrUtil.isEmpty(tradeCode)){
				return Result.error("行业类型不能为空");
			}
			if(StrUtil.isEmpty(address1) || StrUtil.isEmpty(address2) || StrUtil.isEmpty(address3)){
				return Result.error("地址信息-省-市-县不能为空");
			}
			if(StrUtil.isEmpty(linkManAddress)){
				return Result.error("联系人通讯地址不能为空");
			}
		}
		//用户名
		String username = Config.getProp("LIFE_CORE_USERNAME");
		//密码
		String userpsw = Config.getProp("LIFE_CORE_USERPSW");
		//交易码
		String transno = Config.getProp("LIFE_CORE_TRANSRNO");
		String requestXml="";
	 
		//定义发送请求报文字符串
 requestXml = "<?xml version=\"1.0\" encoding=\"GBK\"?>\n"
		+ "<INSUREQRET>\n" + "  <HEAD>\n"
		+ "    <TRANSRNO>"+transno+"</TRANSRNO>\n"
		+ "    <USERNAME>"+username+"</USERNAME>\n"
		+ "    <USERPSW>"+userpsw+"</USERPSW>\n" + "  </HEAD>\n"
		+ "  <MAIN>\n"+"<DEPTNO>"+deptNo+"</DEPTNO>\n"
		+ "    <ORG_PROPERTY>"+orgProperty+"</ORG_PROPERTY>\n"
		+ "    <TRADE_CODE>"+tradeCode+"</TRADE_CODE>\n"
		+ "    <SOCIAL_NO>"+socialNo+"</SOCIAL_NO>\n"
		+ "    <ADDRESS1>"+address1+"</ADDRESS1>\n"
		+ "    <ADDRESS2>"+address2+"</ADDRESS2>\n"
		+ "    <ADDRESS3>"+address3+"</ADDRESS3>\n"
		+ "    <NAME_EN>"+channelNameEn+"</NAME_EN>\n"
		+ "    <CORPORATION>"+corporateDelegate+"</CORPORATION>\n"
		+ "    <TEL>"+telNo+"</TEL>\n"
		+ "    <FAX>"+faxNo+"</FAX>\n"
		+ "    <POSTCODE>"+postCode+"</POSTCODE>\n"
		+ "    <ADDRESS>"+address+"</ADDRESS>\n"
		+ "    <CERTIFICATE_TYPE>"+linkManCertificateType+"</CERTIFICATE_TYPE>\n"
		+ "    <CERTIFICATE_NO>"+linkManCertificateNo+"</CERTIFICATE_NO>\n"
		+ "    <LINKMAN>"+linkManName+"</LINKMAN>\n"
		+ "    <LINKMAN_TEL>"+linkManName+"</LINKMAN_TEL>\n"
		+ "    <LINKMAN_ADDRESS>"+linkManAddress+"</LINKMAN_ADDRESS>\n"
		+ "    <LINKMAN_POSTCODE>"+linkManPostCode+"</LINKMAN_POSTCODE>\n"
		+ "    <LINKMAN_MOBILE>"+linkManMobileNo+"</LINKMAN_MOBILE>\n"
		+ "    <CITY>"+city+"</CITY>\n"
		+ "    <ORG_NAME>"+channelName+"</ORG_NAME>\n"
		+ "	   <GRP_CERT_TYPE>"+idType+"</GRP_CERT_TYPE>\n" 
		+ "    <GRP_CERT_NO>"+idNo+"</GRP_CERT_NO>\n"
		+ "	 </MAIN>\n"
		+ "</INSUREQRET>";
 		//返回响应报文字符串
		// modified by guozizhou@20150409 for bei jing code end
		logger.info("----------------------------------报文------------------------------：\n"+requestXml);
		String responseXMLStr = LifeCoreClient.sendToCicHealth(requestXml);
		
		logger.info("----------------------------------响应报文------------------------------：\n"+responseXMLStr);
		
    	Document doc = null;
    	String clientNo = null;
			doc = DocumentHelper.parseText(responseXMLStr); // 将返回的报文字符串转为XML
			Element root = doc.getRootElement();	//获取根节点
			 Iterator iter = root.elementIterator("MAIN"); // 获取根节点下的子节点MAIN
			 //遍历MAIN节点下子节点
			 while(iter.hasNext()){
				 Element et = (Element)iter.next();
				 clientNo = et.elementText("CLIENTNO");
			 }

			 if(StrUtil.isEmpty(clientNo)){
				 return Result.error("生成投保人编码失败");
			 }else{
				 GatewayChannelInfo channelInfo = new GatewayChannelInfo();
				 channelInfo.setClientNo(clientNo);
				 channelInfo.setIdType(idType);
				 channelInfo.setIdNo(idNo);
				 channelInfo.setAddress1(address1);
				 channelInfo.setAddress2(address2);
				 channelInfo.setAddress3(address3);
				 channelInfo.setOrgProperty(orgProperty);
				 channelInfo.setTradeCode(tradeCode);
				 channelInfo.setSocialNo(socialNo);
				 channelInfo.setChannelCode(channelCode);
				 channelInfo.setOperTime(new Date());
				 //--
				 channelInfo.setCity(city);
				 channelInfo.setChannelNameEn(channelNameEn);
				 channelInfo.setCorporateDelegate(corporateDelegate);
				 channelInfo.setTelNo(telNo);
				 channelInfo.setFaxNo(faxNo);
				 channelInfo.setPostCode(postCode);
				 channelInfo.setAddress(address);
				 channelInfo.setLinkManName(linkManName);
				 channelInfo.setLinkManCertificateType(linkManCertificateType);
				 channelInfo.setLinkManCertificateNo(linkManCertificateNo);
				 channelInfo.setLinkManMobileNo(linkManMobileNo);
				 channelInfo.setLinkManTel(linkManTel);
				 channelInfo.setLinkManAddress(linkManAddress);
				 channelInfo.setLinkManPostCode(linkManPostCode);
				 channelInfoConfigService.saveOrUpdateChannelInfo(channelInfo, "update");
				 if("reCreate".equals(createClientNoFlag)){
					 TradInsuPlan insuplan = new TradInsuPlan();
					 insuplan.setApplicantNo(clientNo);
					 insuplan.setPartnerNo(channelCode);
					 gatewayInsureService.updateTradInsuPlanApplicationNo(insuplan);
				 }
				 return Result.success("生成投保人编码成功");
			 }
	}

	//added by gzz@2015-04-30 begin
	@RequestMapping("/appDeployHandle")
	public String appDeployHandle(ModelMap model,String channelCode) throws Exception {
		if (StrUtil.isNotEmpty(channelCode)) {
			GatewayChannelInfo temInfo = channelInfoConfigService.queryChannelInfoByChannelCode(channelCode);
			if (null != temInfo) {
				model.put("channelCode", channelCode);
				model.put("deptCode", temInfo.getDeptCode());
				model.put("channelName", temInfo.getChannelName());
			}
		}
	   return "appManage/applicationDeploy";
	}
	
	@RequestMapping("/queryChannelAppInfoByCodeAndId")
	@ResponseBody
	public GatewayChannelApp queryChannelAppInfoByCodeAndId(GatewayChannelApp gca) throws Exception{
		GatewayChannelApp returnObj = gatewayChannelAppService.queryChannelAppInfoByCodeAndId(gca);
		return returnObj;
	}
	
	
	@RequestMapping("/saveOrUpdateChannelAppInfo")
	@ResponseBody
	public Result saveOrUpdateChannelAppInfo(HttpSession session, String channelCode,String appId, String flag,String preAppId,String deptCode) throws Exception{
		if(!(channelInfoConfigService.checkIsHasPrivilege(session, deptCode))){
			return Result.error("权限不足，无权操作该合作伙伴!");
		}else if (StrUtil.isEmpty(flag)) {
			return Result.error("系统异常");
		} else if (StrUtil.isEmpty(channelCode)) {
			return Result.error("合作伙伴代码不能为空");
		} else if (StrUtil.isEmpty(appId)) {
			return Result.error("请选择所属应用接口");
		}
		GatewayUser user = (GatewayUser) session.getAttribute(Constants.SESSION_USER);
		GatewayChannelApp gca = new GatewayChannelApp();
		gca.setChannelCode(channelCode);
		gca.setAppId(appId);
		gca.setOperUser(user.getUserid());
		gca.setOperTime(new Date());
		gca.setPreAppId(preAppId);
		if("save".equalsIgnoreCase(flag))
		{
			if(gatewayChannelAppService.add(gca))
			{
				clearAllCacheByChannelCode(channelCode);
				return Result.success("添加成功！");
			}
		}
		if("update".equalsIgnoreCase(flag))
		{
			if(gatewayChannelAppService.update(gca))
			{
				//del transtype
				GatewayChannelTranstype gct = new GatewayChannelTranstype();
				gct.setFkChannelCode(channelCode);
				gct.setAppId(preAppId);
				channelInfoConfigService.delTransTypeByChannelCodeAndAppId(gct);
				clearAllCacheByChannelCode(channelCode);
				return Result.success("修改成功！");
			}
		}
		return null;
	}
	
	@RequestMapping("/deleteChannelAppInfo")
	@ResponseBody
	public Result deleteChannelAppInfo(HttpSession session, String channelCode,String appId, String deptCode) throws Exception{
		if(!(channelInfoConfigService.checkIsHasPrivilege(session, deptCode))){
			return Result.error("权限不足，无权操作该合作伙伴!");
		}else if (StrUtil.isEmpty(channelCode)) {
			return Result.error("合作伙伴代码不能为空");
		} else if (StrUtil.isEmpty(appId)) {
			return Result.error("所属应用接口不能为空");
		}
		GatewayChannelApp gca = new GatewayChannelApp();
		gca.setChannelCode(channelCode);
		gca.setAppId(appId);
		if (gatewayChannelAppService.delete(gca)) {
			//del transtype
			GatewayChannelTranstype gct = new GatewayChannelTranstype();
			gct.setFkChannelCode(channelCode);
			gct.setAppId(appId);
			channelInfoConfigService.delTransTypeByChannelCodeAndAppId(gct);
			clearAllCacheByChannelCode(channelCode);
			return Result.success("删除成功");
		}
		return null;
	}
	
	@RequestMapping("/queryAppInfoByChannelCode")
	@ResponseBody
	public Page queryAppInfoByChannelCode(Integer pageIndex,String channelCode) throws Exception{
		Page channelInfoPage =null;
		if(StrUtil.isNotEmpty(channelCode))
		{
		   channelInfoPage = channelInfoConfigService.queryAppInfoByChannelCode(pageIndex, channelCode);
		}
		return channelInfoPage;
	}
	@RequestMapping(value = "/loadChannelClientNoInfo")
	public @ResponseBody String loadChannelClientNoInfo(String channelCode) throws Exception{
		GatewayChannelInfo channelInfo= channelInfoConfigService.queryChannelInfoByChannelCode(channelCode);
		return JsonUtils.toJson(channelInfo);
	}
	
	/**
	 * 新增saveChannelKey
	 * @param publickey
	 * @param privatekey
	 * @param cooperatepublickey
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/saveChannelKey")
	@ResponseBody
	public Result saveChannelKey(String publickey,String privatekey, String cooperatepublickey,String fkChannelCode,String flag) throws Exception{
	
		GatewayChannelInfo channelInfo = new GatewayChannelInfo();
		channelInfo.setPublicKey(publickey);
		channelInfo.setPrivateKey(privatekey);
		channelInfo.setCooperatepublicKey(cooperatepublickey);
		channelInfo.setChannelCode(fkChannelCode);
		//System.out.println(flag);
		if("save".equals(flag)){
			channelInfoConfigService.saveOrUpdateChannelInfo(channelInfo,"update");
			return Result.success("添加成功");
		}else{
			channelInfoConfigService.saveOrUpdateChannelInfo(channelInfo,"update");
			return Result.success("修改成功");
		}
	}
	
	//added by gzz@2015-04-30 end
	
	//合作伙伴配置缓存管理公共方法
	public void clearAllCacheByChannelCode(String channelCode) throws Exception {
		//查询应用by：channelCode
		List<GatewayChannelApp> appLs = gatewayChannelAppDao.queryChannelAppInfoListByChannelCode(channelCode);
		if(null!=appLs && appLs.size()>0){
			for(GatewayChannelApp tem :appLs){
				gatewayClearCacheManager.clearAllCache(tem.getAppId());
			}
		}
	}
	
	//新增合作伙伴需求配置
	@RequestMapping("/demandConfigPage")
	public String channelDemandConfig(Model model) throws Exception{
		//获取合作伙伴分类信息
		List<DictDto> channelSortList = DictCache.getDict(Constants.DICT_CHANNEL_SORT);
		GatewayChannelDemandConfig info = new GatewayChannelDemandConfig();
		List<GatewayChannelDemandConfig> infos = channelInfoConfigService.selectVersionInfo(info);
		ArrayList<String> list = new ArrayList<String>();
		for (GatewayChannelDemandConfig gatewayChannelDemandConfig : infos) {
			list.add(gatewayChannelDemandConfig.getChannelVersion());
		}
		model.addAttribute("channelSortList", channelSortList);
		
		model.addAttribute("infos", list);
		return "appManage/channelDemandConfig";
	}
	/**
	 * 合作伙伴需求配置分页查询
	 * @param session
	 * @param page
	 * @param demandConfig
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/queryDemandList")
	@ResponseBody
	public Page<GatewayChannelDemandConfig> queryDemandListPage(HttpSession session, Page<GatewayChannelDemandConfig> page,GatewayChannelDemandConfig demandConfig,String premiumBeginDate,String premiumEndDate) throws Exception{
		 Map<String,Object> paramMap = SqlUtil.buildPageMap(page);
		    if(StrUtil.isNotEmpty(demandConfig.getChannelCode())){
		        paramMap.put("channelCode", demandConfig.getChannelCode());  
		    }
		    if(StrUtil.isNotEmpty(demandConfig.getChannelSort())){
		        paramMap.put("channelSort", demandConfig.getChannelSort());  
		    }
		    if(StrUtil.isNotEmpty(demandConfig.getChannelVersion())){
		        paramMap.put("channelVersion", demandConfig.getChannelVersion());  
		    }
		    if(StrUtil.isNotEmpty(demandConfig.getDemandName())){
		        paramMap.put("demandName", demandConfig.getDemandName());  
		    }
		    if(StrUtil.isNotEmpty(premiumBeginDate)){
		    	paramMap.put("premiumBeginDate",premiumBeginDate);
		    }
		    if(StrUtil.isNotEmpty(premiumEndDate)){
		    	paramMap.put("premiumEndDate", premiumEndDate);

		    }
		    if(StrUtil.isNotEmpty(demandConfig.getPartnerNumber())){
		    paramMap.put("partnerNumber", demandConfig.getPartnerNumber());

		    }
		    page.setMap(paramMap);
	 Page<GatewayChannelDemandConfig> data = channelInfoConfigService.queryDemandList(page);
		return data;
	}
	@RequestMapping("/ajaxSelectChannelCode")
	@ResponseBody
	public List<GatewayChannelDemandConfig> ajaxSelectChannelCode(String channelCode)throws Exception{
		GatewayChannelDemandConfig info = new GatewayChannelDemandConfig();
		if(StrUtil.isNotEmpty(channelCode)){
			info.setChannelCode(channelCode+"%");
		}
		List<GatewayChannelDemandConfig> partnerInfo = channelInfoConfigService.selectPartnerInfo(info);
		return partnerInfo;
	}
	@RequestMapping("/ajaxSelectChannelVersion")
	@ResponseBody
	public List<GatewayChannelDemandConfig> ajaxSelectChannelVersion(String versionNo)throws Exception{
		GatewayChannelDemandConfig info = new GatewayChannelDemandConfig();
		if(StrUtil.isNotEmpty(versionNo)){
			info.setChannelVersion(versionNo+"%");
		}
		List<GatewayChannelDemandConfig> versionInfo = channelInfoConfigService.selectVersionInfo(info);
		return versionInfo;
	}
	@RequestMapping("/ajaxSelectDemandName")
	@ResponseBody
	public List<GatewayChannelDemandConfig> ajaxSelectDemandName(String demandName)throws Exception{
		GatewayChannelDemandConfig info = new GatewayChannelDemandConfig();
		if(StrUtil.isNotEmpty(demandName)){
			info.setDemandName(demandName+"%");
		}
		List<GatewayChannelDemandConfig> demandInfo = channelInfoConfigService.selectDemandInfo(info);
		return demandInfo;
	}
	@RequestMapping("/ajaxSelectDemandNumber")
	@ResponseBody
	public List<GatewayChannelDemandConfig> ajaxSelectPartnerNumber(String partnerNumber)throws Exception{
		GatewayChannelDemandConfig info = new GatewayChannelDemandConfig();
		if(StrUtil.isNotEmpty(partnerNumber)){
			info.setPartnerNumber(partnerNumber+"%");;
		}
		List<GatewayChannelDemandConfig> demandInfo = channelInfoConfigService.selectDemandInfo(info);
		return demandInfo;
	}
	//合作伙伴需求配置模板下载
	@RequestMapping("/demandExcelDownload")
	public void downloadUserTemplet(HttpServletResponse response,HttpServletRequest request) throws IOException{
		String classPath=this.getClass().getResource("").getPath();
		String path="";
			path = (classPath.substring(0,classPath.indexOf("/WEB-INF/")+8)+ "/file/demandImport_template.xls").replace("/WEB-INF", "");
		// 以流的形式下载文件
		InputStream inputStream=null;
		OutputStream outputStream =null;
		try {
			File file = new File(path);
			// 取得文件名。
			String filename = file.getName();
			inputStream = new BufferedInputStream(new FileInputStream(path));
			byte[] buffer = new byte[inputStream.available()];
			inputStream.read(buffer);
			response.reset();
			response.addHeader("Content-Disposition", "attachment;filename=" + new String(filename.getBytes()));
			response.addHeader("Content-Length", "" + file.length());
			outputStream = new BufferedOutputStream(response.getOutputStream());
			response.setContentType("application/octet-stream");
			outputStream.write(buffer);
			outputStream.flush();
		}catch (Exception e) {
			logger.info(e);
		}finally{
			if(null!=inputStream){
				inputStream.close();
			}
			if(null!=outputStream){
				outputStream.close();
			}
		}
	}
	/***
	 * 需求新增
	 * @param demands
	 * @param session
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/addDemands")
	@ResponseBody
	public Result addDemands(@RequestBody List<GatewayChannelDemandConfig> demands,HttpSession session) throws Exception{
		GatewayUser gatewayuser=(GatewayUser) session.getAttribute(Constants.SESSION_USER);
		ArrayList<GatewayChannelDemandConfig> list = new ArrayList<GatewayChannelDemandConfig>();
		for (GatewayChannelDemandConfig demand : demands) {
			demand.setOperUser(gatewayuser.getUserCode());
			demand.setOperTime(new Date());
			list.add(demand);
		}
		 String message = channelInfoConfigService.insertChannelDemands(list);
		return Result.data(message);
	}
	@RequestMapping("/addVersions")
	@ResponseBody
	public Result addVersions(HttpSession session, GatewayChannelDemandConfig gatewayChannelDemandConfig){
		GatewayUser gatewayuser=(GatewayUser) session.getAttribute(Constants.SESSION_USER);
		gatewayChannelDemandConfig.setOperUser(gatewayuser.getUserCode());
		gatewayChannelDemandConfig.setOperTime(new Date());
		String str = channelInfoConfigService.insertVersion(gatewayChannelDemandConfig);
		return Result.data(str);
	}
	@RequestMapping("/queryDemandForUpdate")
	@ResponseBody
	public GatewayChannelDemandConfig selectChannelDemandForUpdate(String id)throws Exception{
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("id", id);
		GatewayChannelDemandConfig data = channelInfoConfigService.queryDemandForUpdate(map);
		return data;
	}
	@RequestMapping("/updateChannelDemand")
	@ResponseBody
	public Result updateChannelDemand(HttpSession session,GatewayChannelDemandConfig gatewayChannelDemandConfig) throws Exception{
		GatewayUser gatewayuser=(GatewayUser) session.getAttribute(Constants.SESSION_USER);
		gatewayChannelDemandConfig.setOperUser(gatewayuser.getUserCode());
		gatewayChannelDemandConfig.setOperTime(new Date());
		int queryVersionExist = channelInfoConfigService.queryVersionExist(gatewayChannelDemandConfig.getChannelVersion());
		if(queryVersionExist!=0){
			boolean result = channelInfoConfigService.updateChannelDemand(gatewayChannelDemandConfig);
			ArrayList<GatewayChannelDemandConfig> costList = new ArrayList<GatewayChannelDemandConfig>();
			boolean flag=true;
			if (gatewayChannelDemandConfig.getPartnerSystem()!=null) {
				GatewayChannelDemandConfig cost = new GatewayChannelDemandConfig();
				cost.setId(gatewayChannelDemandConfig.getId());
				cost.setSystemCode("PARTNERSYSTEM");
				cost.setChannelCost(gatewayChannelDemandConfig.getPartnerSystem());
				cost.setOperUser(gatewayChannelDemandConfig.getOperUser());
				cost.setOperTime(gatewayChannelDemandConfig.getOperTime());
				costList.add(cost);
			}
			if (gatewayChannelDemandConfig.getNlifeSystem()!=null) {
				GatewayChannelDemandConfig cost = new GatewayChannelDemandConfig();
				cost.setId(gatewayChannelDemandConfig.getId());
				cost.setSystemCode("NLIFESYSTEM");
				cost.setChannelCost(gatewayChannelDemandConfig.getNlifeSystem());
				cost.setOperUser(gatewayChannelDemandConfig.getOperUser());
				cost.setOperTime(gatewayChannelDemandConfig.getOperTime());
				costList.add(cost);
			}
			if (gatewayChannelDemandConfig.getCoreFive()!=null) {
				GatewayChannelDemandConfig cost = new GatewayChannelDemandConfig();
				cost.setId(gatewayChannelDemandConfig.getId());
				cost.setSystemCode("COREFIVE");
				cost.setChannelCost(gatewayChannelDemandConfig.getCoreFive());
				cost.setOperUser(gatewayChannelDemandConfig.getOperUser());
				cost.setOperTime(gatewayChannelDemandConfig.getOperTime());
				costList.add(cost);
			}
			if (gatewayChannelDemandConfig.getCoreSeven()!=null) {
				GatewayChannelDemandConfig cost = new GatewayChannelDemandConfig();
				cost.setId(gatewayChannelDemandConfig.getId());
				cost.setSystemCode("CORESEVEN");
				cost.setChannelCost(gatewayChannelDemandConfig.getCoreSeven());
				cost.setOperUser(gatewayChannelDemandConfig.getOperUser());
				cost.setOperTime(gatewayChannelDemandConfig.getOperTime());
				costList.add(cost);
			}
			if (gatewayChannelDemandConfig.getePolicySystem()!=null) {
				GatewayChannelDemandConfig cost = new GatewayChannelDemandConfig();
				cost.setId(gatewayChannelDemandConfig.getId());
				cost.setSystemCode("EPOLICYSYSTEM");
				cost.setChannelCost(gatewayChannelDemandConfig.getePolicySystem());
				cost.setOperUser(gatewayChannelDemandConfig.getOperUser());
				cost.setOperTime(gatewayChannelDemandConfig.getOperTime());
				costList.add(cost);
			}
			for (GatewayChannelDemandConfig info : costList) {
				boolean updateDemandCost = channelInfoConfigService.updateDemandCost(info);
				if(!updateDemandCost){
					flag=false;
				}
			}
			
			if(result&&flag){
				return Result.data("success");
			}else{
				return Result.data("error");	
			}
		}else{
			return Result.data("exit");
		}

	}
	@RequestMapping("/demandDelete")
	@ResponseBody
	public Result demandDelete(String id) throws Exception{
		Map<String, Object> map = new HashMap<String, Object>();
		if(StrUtil.isNotEmpty(id)){
			map.put("id", id);
		}
		boolean flag = channelInfoConfigService.deleteChannelDemands(map);
		boolean costFlag=false;
		if(flag){
		    costFlag = channelInfoConfigService.deleteChannelCosts(map);
		}
		if(flag&&costFlag){
			return Result.data("success");
		}else{
			return Result.data("error");	
		}
	}
	@RequestMapping("/delDemandCost")
	@ResponseBody
	public Result delDemandCost(String id,String systemCode) throws Exception{
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("id", id);
		map.put("systemCode", systemCode);
		boolean flag = channelInfoConfigService.deleteChannelCosts(map);
		if(flag){
			return Result.data("success");
		}else{
			return Result.data("error");	
		}
	}
	@RequestMapping("/queryDemandCostList")
	@ResponseBody
	public Page<GatewayChannelDemandConfig> selectDemandCostList(String id)throws Exception{
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("id", id);
		List<GatewayChannelDemandConfig> list = channelInfoConfigService.selectDemandList(map);
		 Page<GatewayChannelDemandConfig> page = new  Page<GatewayChannelDemandConfig>();
		 page.setData(list);
		return page;
	}
	
	@RequestMapping("/querySystemName")
	@ResponseBody
	public List<DictDto> selectSystemName(String id)throws Exception{
		String sql = "select * from t_gateway_dict d where d.code_type = 'DICT_SYSTEM_NAME' and d.code not in(select c.SYSTEM_CODE from t_gateway_channel_cost c where c.id ="+id+")";
		List<DictDto> dict1 = DictCache.getDict1("DICT_SYSTEM_NAME", sql);
		return dict1;
	}
	@RequestMapping("/saveDemandCost")
	@ResponseBody
	public Result addDemandCost(HttpSession session,GatewayChannelDemandConfig config)throws Exception{
		GatewayUser gatewayuser=(GatewayUser) session.getAttribute(Constants.SESSION_USER);
		config.setOperUser(gatewayuser.getUserCode());
		config.setOperTime(new Date());
		String insertDemandCost = channelInfoConfigService.insertDemandCost(config);
		return Result.data(insertDemandCost);
	}
	@RequestMapping("/demandExcelImport")
	public void demandsImport(@RequestParam MultipartFile[] excelFile,HttpServletResponse response, HttpSession session) throws Exception {
		response.setContentType("text/html");
		response.setCharacterEncoding("UTF-8");
		PrintWriter out = null;
		List<InputStream> inputStreams = null;
		Page<String>  page = new Page<String>();
		GatewayChannelDemandConfig info = new GatewayChannelDemandConfig();
		List<GatewayChannelDemandConfig> infos = channelInfoConfigService.selectVersionInfo(info);
		List<String> list = new ArrayList<String>();
		for (GatewayChannelDemandConfig gatewayChannelDemandConfig : infos) {
			list.add(gatewayChannelDemandConfig.getChannelVersion());
		}
		// 上传文件的原名(即上传前的文件名字)
		try {
			out = response.getWriter();
			if (excelFile.length < 1) {
				page.setResult("error");
				page.setMessage("请添加上传文件!");
			}else{
				GatewayUser user = (GatewayUser)session.getAttribute(Constants.SESSION_USER);
				inputStreams=channelInfoConfigService.getFileInputStream(excelFile);
				channelInfoConfigService.importExcelForDemand(inputStreams.get(0), user, session,list);
				logger.info("需求清单读写成功");
				page.setResult("success");
				page.setMessage("导入成功");
			}
		} catch (Exception e) {
			logger.info("---------Excel导入失败",e);
			page.setResult("error");
			page.setMessage(e.getMessage());
		} finally {
			if(null!=inputStreams){
				for (InputStream input:inputStreams){
					try{
						input.close();
					}catch(Exception e){
						logger.warn("关闭流失败！", e);
					}
				}
			}
			out.write(JsonUtils.toJson(page));
			try {
				out.close();
			} catch (Exception e) {
				logger.warn("关闭流失败！", e);
			}
		}
	}
	
	@RequestMapping("/demandExportExcel")
	@ResponseBody
	public void exportCardExcel(HttpSession session,HttpServletRequest request, HttpServletResponse resp,String premiumBeginDate,String premiumEndDate, GatewayChannelDemandConfig demand) throws Exception {
		Map<String, Object> parametermap=new HashMap<String,Object>();
		String channelCodeStr="";
		List<String> channelCodes =  new ArrayList<String>();
		parametermap.put("premiumBeginDate",premiumBeginDate);
		parametermap.put("premiumEndDate", premiumEndDate);
		parametermap.put("channelSort", demand.getChannelSort());
		parametermap.put("channelVersion", demand.getChannelVersion());
		if(StrUtil.isNotEmpty(demand.getDemandName())){
			String demandName = URLDecoder.decode(demand.getDemandName(),"utf-8");
			parametermap.put("demandName", demandName+"%");	
		}
		parametermap.put("partnerNumber", demand.getPartnerNumber());
		if(StrUtil.isNotEmpty(demand.getChannelCode())){
			parametermap.put("channelCodeStr",channelCodeStr+="'"+demand.getChannelCode()+"',");
			channelCodes.add(demand.getChannelCode());
		}else{
			channelCodes=channelInfoConfigService.queryDemandChannelCode(parametermap);
			if(channelCodes.size()>0){
				for (String str : channelCodes) {
					channelCodeStr+="'"+str+"',";
				}	
			}
		}
		if(StrUtil.isNotEmpty(channelCodeStr)){
			channelCodeStr=channelCodeStr.substring(0,channelCodeStr.length()-1);
			parametermap.put("channelCodeStr", channelCodeStr);
		}
		parametermap.put("premiumBeginDate",premiumBeginDate);
		parametermap.put("premiumEndDate", premiumEndDate);

		List<GatewayChannelDemandConfig> demandExportList = channelInfoConfigService.demandExportSelect(parametermap);

		Map<String, String[][]> maps = new HashMap<String, String[][]>();
		List<String[]> lists = null;
		String fileName = "合作伙伴投产比统计";
		for (int i = 0; i < channelCodes.size(); i++) {
			lists = new ArrayList<String[]>();
			for (GatewayChannelDemandConfig demandExcel : demandExportList) {
					if (channelCodes.get(i).equals(demandExcel.getChannelCode())) {
						if(demandExcel.getSumPremium()==null){
							demandExcel.setSumPremium(new BigDecimal("0"));
						}
						lists.add(new String[] { demandExcel.getProdCode(),demandExcel.getChannelCode(),demandExcel.getChannelName(),demandExcel.getProdCode(),demandExcel.getInsertTime(),String.valueOf(demandExcel.getSumPremium().divide(new BigDecimal(10000))),(demandExcel.getChannelCost()==null)?"":String.valueOf(demandExcel.getChannelCost())});
				}
			}
				maps.put(channelCodes.get(i), lists.toArray(new String[0][0]));
		}
		String sheetName = "合作伙伴投产比统计";
		String titleName = "合作伙伴投产比统计";
		int columnNumber = 7;
		int[] columnWidth = { 20, 20, 40, 20, 20, 20, 20 };
		String[] columnName = { "产品线", "合作方代码", "合作方名称", "上线产品", "上线时间","保费金额（万元）", "投入金额（万元）" };
		HSSFWorkbook wb = new HSSFWorkbook();
		HSSFSheet sheet = wb.createSheet(sheetName);
		for (int i = 0; i < columnNumber; i++) {
			for (int j = 0; j <= i; j++) {
				if (i == j) {
					sheet.setColumnWidth(i, columnWidth[j] * 256);
				}
			}
		}
		HSSFRow row1 = sheet.createRow((int) 0);
		row1.setHeightInPoints(50);
		HSSFDataFormat createDataFormat = wb.createDataFormat();
		HSSFCellStyle style2 = wb.createCellStyle();
		style2.setDataFormat(createDataFormat.getFormat("@"));
		style2.setAlignment(HSSFCellStyle.ALIGN_CENTER);
		style2.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
		style2.setFillForegroundColor(HSSFColor.GREEN.index);
		style2.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
		HSSFFont headerFont1 = (HSSFFont) wb.createFont();
		headerFont1.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
		headerFont1.setFontName("宋体");
		headerFont1.setFontHeightInPoints((short) 15);
		style2.setFont(headerFont1);
		HSSFCell cell1 = row1.createCell(0);
		sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, columnNumber - 1));
		cell1.setCellValue(titleName);
		cell1.setCellStyle(style2);
		// 第1行
		HSSFRow row = sheet.createRow((int) 1);
		// 表头高度
		row.setHeightInPoints(37);
		// 表头单元格样式 以及表头的字体样式
		HSSFCellStyle style = wb.createCellStyle();
		// 自动换行
		style.setWrapText(true);
		// 居中格式
		style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
		style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
		style.setBottomBorderColor(HSSFColor.BLACK.index);
		style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
		style.setBorderLeft(HSSFCellStyle.BORDER_THIN);
		style.setBorderRight(HSSFCellStyle.BORDER_THIN);
		style.setBorderTop(HSSFCellStyle.BORDER_THIN);
		HSSFFont headerFont = (HSSFFont) wb.createFont();
		// 字体加粗
		headerFont.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
		// 设置字体类型
		headerFont.setFontName("宋体");
		// 设置字体大小
		headerFont.setFontHeightInPoints((short) 10);
		// 为标题样式设置字体样式
		style.setFont(headerFont);
		HSSFCell cell = null;
		for (int i = 0; i < columnNumber; i++) {
			cell = row.createCell(i);
			cell.setCellValue(columnName[i]);
			cell.setCellStyle(style);
		}
		// 创建单元格
		// 为数据内容设置特点新单元格样式1 自动换行 上下居中
		HSSFCellStyle cellStyle = wb.createCellStyle();
		cellStyle.setWrapText(true);// 设置自动换行
		cellStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER); // 创建一个居中格式
		// 设置边框
		cellStyle.setBottomBorderColor(HSSFColor.BLACK.index);
		cellStyle.setBorderBottom(HSSFCellStyle.BORDER_THIN);
		cellStyle.setBorderLeft(HSSFCellStyle.BORDER_THIN);
		cellStyle.setBorderRight(HSSFCellStyle.BORDER_THIN);
		cellStyle.setBorderTop(HSSFCellStyle.BORDER_THIN);
		HSSFCellStyle cellStyle1 = wb.createCellStyle();
		cellStyle1.setWrapText(true);// 设置自动换行
		cellStyle1.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER); // 创建一个上下居中格式
		cellStyle1.setAlignment(HSSFCellStyle.ALIGN_CENTER);// 左右居中
		// 设置边框
		cellStyle1.setBottomBorderColor(HSSFColor.BLACK.index);
		cellStyle1.setBorderBottom(HSSFCellStyle.BORDER_THIN);
		cellStyle1.setBorderLeft(HSSFCellStyle.BORDER_THIN);
		cellStyle1.setBorderRight(HSSFCellStyle.BORDER_THIN);
		cellStyle1.setBorderTop(HSSFCellStyle.BORDER_THIN);
		cellStyle1.setDataFormat(createDataFormat.getFormat("@"));
		int flag = 0;
		int temp=2;
		for (String str : maps.keySet()) {
			for (int i = 0; i < maps.get(str).length; i++) {
				row = sheet.createRow(flag + 2);
				HSSFCell datacell = null;
				for (int j = 0; j < columnNumber; j++) {
					datacell = row.createCell(j);
					datacell.setCellValue(maps.get(str)[i][j]);
					datacell.setCellStyle(cellStyle1);
				}
				flag++;
			}
			if(maps.get(str).length>1){
				sheet.addMergedRegion(new CellRangeAddress(temp,((temp+maps.get(str).length)-1),6,6));
			}
			temp+=maps.get(str).length;
		}
		resp.setContentType("application/ms-excel;charset=UTF-8");
		resp.setHeader("Content-Disposition", "attachment;filename="+ new String(fileName.getBytes(), "iso-8859-1") + ".xls");
		OutputStream out = resp.getOutputStream();
		try {
			wb.write(out);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			out.close();
		}

	}
	
	/**
	 * 跳转到 合作伙伴属性 页面
	 */
	@RequestMapping("/channelAttribute")
	public String channelAttribute(ModelMap model) throws Exception {
		//获取合作伙伴分类信息
		List<DictDto> channelSortList = DictCache.getDict(Constants.DICT_CHANNEL_SORT);
		model.put("channelSortList", channelSortList);
	   return "appManage/channelAttribute";
	}
	/**
	 * 添加channelInfo
	 */
	@RequestMapping("/saveOrUpdateChannelAttribute")
	@ResponseBody
	public Result saveOrUpdateChannelAttribute(HttpSession session,GatewayChannelInfo channelInfo,String flag) throws Exception{
		if(channelInfo==null) {
			return Result.error("获取合作伙伴信息失败");
		}else if(!(channelInfoConfigService.checkIsHasPrivilege(session, channelInfo.getDeptCode()))){
			return Result.error("权限不足，无权操作该合作伙伴!");
		}else if(StrUtil.isEmpty(flag)){
			return Result.error("系统异常");
		}else if(StrUtil.isEmpty(channelInfo.getChannelCode())){
			return Result.error("合作伙伴代码不能为空");
		}else if(!channelInfo.getChannelCode().matches("^[a-zA-Z_0-9]{1,30}$")){
			return Result.error("合作伙伴代码只支持字母数字下划线组合且长度不能大于30");
		}else if(StrUtil.isEmpty(channelInfo.getDeptCode())){
			return Result.error("请选择所属机构");
		}
		
//		GatewayUser user = (GatewayUser) session.getAttribute(Constants.SESSION_USER);
//		Long operUser = user.getUserid();
//		Date operTime = new Date();
//		String status = "1";

		//添加或者更新顶级信息到DB
//		GatewaySubChannel subChannel =   new GatewaySubChannel();
//		subChannel.setSubChannelCode(channelInfo.getChannelCode());
//		subChannel.setFkChannelCode(channelInfo.getChannelCode());
//		subChannel.setStatus(status);
//		subChannel.setOperTime(operTime);
//		subChannel.setOperUser(operUser);
//		if("update".equalsIgnoreCase(flag))
//		{
//	 		subChannelService.saveOrUpdateSubChannel(subChannel, flag);
//		}
		GatewayChannelInfo gatewayChannelInfo = queryChannelInfoByChannelCode(channelInfo.getChannelCode());
		if(gatewayChannelInfo != null && flag.equals("update")) {
			channelInfo.setDeptCode(null);//有些值不进行修改
			channelInfoConfigService.saveOrUpdateChannelInfoToURL(channelInfo,flag);
			return Result.success("修改成功！");
		}else if(gatewayChannelInfo == null){
			return Result.success("查询合作伙伴信息失败！");
		}
		return null;
	}
}

